/*
 * Copyright (c) 2018-2999 北京小象智慧信息科技有限公司 All rights reserved.
 *
 * https://www.xiaoxiangai.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.security.handler;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.CharsetUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import com.yami.shop.bean.model.LoginHist;
import com.yami.shop.common.util.HttpClient;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.dao.LoginHistMapper;
import com.yami.shop.security.config.TokenConfig;
import com.yami.shop.security.model.AppConnect;
import com.yami.shop.security.service.AppConnectService;
import com.yami.shop.security.service.YamiSysUser;
import com.yami.shop.security.service.YamiUser;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 登录成功，返回oauth token
 *
 */
@Component
@Slf4j
public class LoginAuthSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private LoginHistMapper loginHistMapper;
    @Autowired
    @Lazy
    private AuthorizationServerTokenServices yamiTokenServices;

    @Autowired
    private AppConnectService appConnectService;

    /**
     * Called when a user has been successfully authenticated.
     * 调用spring security oauth API 生成 oAuth2AccessToken
     *
     * @param request        the request which caused the successful authentication
     * @param response       the response
     * @param authentication the <tt>Authentication</tt> object which was created during
     */
    @Override
    @Transactional
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

        try {

            TokenRequest tokenRequest = new TokenRequest(null, null, null, null);

            // 简化
            OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(new BaseClientDetails());
            OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);

            OAuth2AccessToken oAuth2AccessToken = yamiTokenServices.createAccessToken(oAuth2Authentication);
            if(authentication.getDetails()!=null) {
                if (authentication.getDetails().equals("offline")) {
                    //新增登陆用户信息
                    YamiSysUser yamiUser = (YamiSysUser) authentication.getPrincipal();
                    LoginHist loginHist = new LoginHist();
                    loginHist.setUserId(String.valueOf(yamiUser.getUserId()));
                    loginHist.setLoginTime(new Date());
                    loginHist.setAccessToken(oAuth2AccessToken.getValue());
                    loginHistMapper.insertLoginLog(loginHist);
                }else if(authentication.getDetails().equals("api")){
                    YamiUser user = (YamiUser)authentication.getPrincipal();
                    String userId = user.getBizUserId();
                    AppConnect appConnect = appConnectService.getAppConncetByBizUserId(userId);
                    if(appConnect!=null) {
                        appConnect.setToken(oAuth2AccessToken.getValue());
                        appConnectService.saveOrUpdate(appConnect);
                    }
                }
            }else{
//                YamiUser user = (YamiUser)authentication.getPrincipal();
//                String userId = user.getBizUserId();
//                AppConnect appConnect = appConnectService.getAppConncetByBizUserId(userId);
//                if(appConnect!=null) {
//                    appConnect.setToken(oAuth2AccessToken.getValue());
//                    appConnectService.saveOrUpdate(appConnect);
//                }
            }

            log.info("获取token 成功：{}", oAuth2AccessToken.getValue());
            response.setCharacterEncoding(CharsetUtil.UTF_8);
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            PrintWriter printWriter = response.getWriter();
            printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken));
        } catch (IOException e) {
            throw new BadCredentialsException(
                    "Failed to decode basic authentication token");
        }

    }


}
